import amap from './blit/amap-wx.130'
let amapPlugin = null
// 高德地图API key
amapPlugin = new amap.AMapWX({
  key: '05d8d3a33246ef33e39d374ac6234b63'
})


// 高德地图获取经纬度 (小程序端之外可使用此aoi获取经纬度)
export const getaddress = () => {
  return new Promise((resolve, reject) => {
    amapPlugin.getRegeo({
      success: (data) => {
        resolve(data[0])
        // this.loadmendian()
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}
// 高德地图规划路线
export const planningRoute = async (end) => {
  const resp = await WXAddress()
  return new Promise((resolve, reject) => {
    amapPlugin.getDrivingRoute({
      origin: resp.longitude + ',' + resp.latitude,
      destination: end,
      success: function (data) {
        var points = []
        if (data.paths && data.paths[0] && data.paths[0].steps) {
          var steps = data.paths[0].steps
          for (var i = 0; i < steps.length; i++) {
            var poLen = steps[i].polyline.split(';')
            for (var j = 0; j < poLen.length; j++) {
              points.push({
                longitude: parseFloat(poLen[j].split(',')[0]),
                latitude: parseFloat(poLen[j].split(',')[1])
              })
            }
          }
        }
        resolve(data)
      },
      fail: function (info) {

        console.log('错误信息：' + info)
        reject(inof)
      }
    })
  })
}




// 全局经纬度信息 BiaoJiDian
export const BiaoJiDian = {
  longitude: '',
  latitude: ''
}

/**
 * WXAddress 此api只能为小程序端
 * @returns {longitude: number,latitude: number,?:?}
 */
/* 请勿随意修改 */
/* 该模块封装获取经纬度方法，支持实时刷新获取最新位置信息 */
export const WXAddress = () => { //速度快
  return new Promise((resolve, reject) => {
    uni.getLocation({
      type: 'wgs84',
      success: function (res) {
        BiaoJiDian.latitude = res.latitude
        BiaoJiDian.longitude = res.longitude
        resolve(res)
      },
      complete: function (error) {
        try {
          if (error.errMsg.toString().length > 0) {
            resolve(getWxLocation())
          }
        } catch (e) {
          reject(e)
        }
        resolve()
      }
    })
  })
}
// 小程序后台获取信息
const getWxLocation = () => { //速度慢
  return new Promise((resolve, reject) => {
    let _locationChangeFn = (res) => {

      BiaoJiDian.latitude = res.latitude
      BiaoJiDian.longitude = res.longitude

      resolve(res)
      wx.offLocationChange(_locationChangeFn)
    }
    wx.startLocationUpdate({
      type: 'wgs84',
      success: (res) => {
        wx.onLocationChange(_locationChangeFn)
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}
